package com.wangshuqi.mybatis.spring;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import java.util.Set;

/*
 * 自定义扫描配置类
 * */
public class MyScanner extends ClassPathBeanDefinitionScanner {

    public MyScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }

    /*
     * 指定扫描包下的接口
     * */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface();
    }


    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
            BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();
            String beanClassName = beanDefinition.getBeanClassName(); // 获取bean类型名称
            // 将bean的类型改为MyFactoryBean
            beanDefinition.setBeanClassName(MyFactoryBean.class.getName());
            // 给对象实例化的构造函数中传入参数
            // 此处传入的是Mapper接口的类型，对应着MyFactoryBean中的private Class mapperClass属性
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
        }
        return beanDefinitionHolders;
    }
}
